<?php

declare(strict_types=1);

namespace common\trait;

use common\attribute\Description;
use ReflectionClass;

trait Enum
{
    /**
     * 获取枚举的描述
     * @return string
     */
    public function getDescription(): string
    {
        $reflection = new ReflectionClass($this);
        $case = $reflection->getReflectionConstant($this->name);
        $attributes = $case->getAttributes(Description::class);
        if (!empty($attributes)) {
            $attribute = $attributes[0]->newInstance();
            return $attribute->value;
        }
        return $this->name;
    }

    /**
     * 获取所有枚举值及其描述信息
     * @return array<string, string>
     */
    public static function getDescriptions(): array
    {
        $result = [];
        foreach (self::cases() as $case) {
            $result[$case->name] = $case->getDescription();
        }
        return $result;
    }

    /**
     * 通过值获取对应的描述
     */
    public static function getDescriptionByValue(int $value): ?string
    {
        return self::tryFrom($value)?->getDescription();
    }

    /**
     * 获取所有枚举值
     * @return array<int, static>
     */
    public static function getValues(): array
    {
        return array_map(fn($case) => $case->value, self::cases());
    }

    /**
     * 检查值是否存在
     */
    public static function hasValue(int $value): bool
    {
        return self::tryFrom($value) !== null;
    }
}